package org.thingsboard.server.dao.jpa.imp;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.thingsboard.server.dao.jpa.TApp;
import org.thingsboard.server.dao.util.SqlDao;

import java.util.List;

@SqlDao
public interface AppRepository extends CrudRepository<TApp,String> {

    @Query("SELECT DISTINCT d FROM TDevice a LEFT JOIN TAreaDevice b on a.deviceId=b.deviceId LEFT JOIN TAppArea c ON b.areaId=c.areaId LEFT JOIN TApp d ON c.appId=d.appId where a.deviceCode = :deviceCode")
    TApp getApp(@Param("deviceCode") String deviceCode);


    @Query("SELECT DISTINCT d FROM TGateway e left join TDevice a on e.gatewayCode=a.gatewayCode LEFT JOIN TAreaDevice b on a.deviceId=b.deviceId LEFT JOIN TAppArea c ON b.areaId=c.areaId LEFT JOIN TApp d ON c.appId=d.appId where e.gatewayCode = :gatewayCode")
    List<TApp> getAppByGatewayCode(@Param("gatewayCode") String gatewayCode);

    @Query("SELECT DISTINCT d FROM TGateway e left join  TGateway f  on e.gatewayId=f.parentId left join TDevice a on f.gatewayCode=a.gatewayCode LEFT JOIN TAreaDevice b on a.deviceId=b.deviceId LEFT JOIN TAppArea c ON b.areaId=c.areaId LEFT JOIN TApp d ON c.appId=d.appId where e.gatewayCode = :gatewayCode ")
    List<TApp> getAppByGatewayCodes(@Param("gatewayCode") String gatewayCode);
}
